//# sourceURL=http://umap.jsmuhang.com/UI/PC/Layer/UavFlightsLayer
(function () {

    Namespace.Class("Umap.UI.PC.Layer", UavFlightsLayer);
    var Interface = Namespace.Import("Umap.Tool.Interface");
    var UavFlight = Namespace.Import("Umap.UI.PC.Layer.UavFlight");
    var Ajax = Namespace.Import("Umap.Tool.Ajax");

    function UavFlightsLayer(option) {

        var _this = this;

        _this.isLoaded = false;
        _this.isOpened = false;
        _this.list = [];
        _this.flights = [];
        _this.currentFlight = undefined;

        _this.dom = $("<div class=\"layer uavLayer\"></div>");
        _this.relocateButton = $("<div class=\"relocateButton\"></div>");

        _this.dom.append(_this.relocateButton).hide();

        _this.relocateButton.click(function () {
            _this.currentFlight && _this.currentFlight.fly();
        });

        option && _this._init(option);

        _this.dataURL = config.getResourcePath(_this.dataURL);
        _this.videoBaseURL = config.getResourcePath(_this.videoBaseURL);

        var viewer = umapEarthJs.earthViewer;

        _this.load = function (onLoad) {

            if (!_this.isLoaded) {

                Ajax({
                    type    : "GET",
                    dataType: "json",
                    url     : _this.dataURL,
                    success : function (json) {
                        if (json.code == 1) {

                            _this.list = json.data.list;

                            $.each(_this.list, function (i, item) {

                                item.videoBaseURL = _this.videoBaseURL;

                                _this.flights[i] = new UavFlight(item);
                                _this.flights[i].index = i;
                                _this.flights[i].load(checkIsAllLoaded);

                                Ajax({
                                    type    : "GET",
                                    dataType: "json",
                                    url     : item.dataUrl,
                                    success : function (json) {
                                        if (json.code == 1) {

                                            item.positions = json.data.positions;

                                            item.position = {
                                                start: item.positions[0],
                                                stop : item.positions[item.positions.length - 1]
                                            };


                                        }
                                    }
                                });

                            });

                            var loaded = 0;

                            function checkIsAllLoaded() {
                                loaded++;
                                if (loaded == _this.list.length) {
                                    _this.isLoaded = true;
                                    onLoad && onLoad();
                                }
                            }

                            Namespace.Import("Umap.UI.PC.VideoPlayer");
                            _this.video = new Umap.UI.PC.VideoPlayer({
                                "title": "无人机视频",
                                "close": true
                            });

                            uiApp.top.append(_this.video.dom);
                            _this.video.hide();

                            _this.video.videoDOM.addEventListener("seeked", function () {
                                uEarth.JulianDate.addSeconds(
                                    _this.currentFlight.startTime,
                                    Math.round(_this.video.videoDOM.currentTime),
                                    viewer.clock.currentTime
                                );

                                if (typeof _this.videoPlaying != undefined) {
                                    _this.video.videoDOM.play();
                                    _this.videoPlaying = undefined;
                                    viewer.clock.shouldAnimate = true;
                                } else {
                                    viewer.clock.shouldAnimate = !_this.video.videoDOM.paused;
                                }

                            }, false);

                            _this.video.videoDOM.addEventListener("pause", function () {
                                viewer.clock.shouldAnimate = false;
                            }, false);

                            _this.video.videoDOM.addEventListener("play", function () {
                                viewer.clock.shouldAnimate = true;
                                // _this.startVideoTitle();
                            }, false);

                            _this.video.videoDOM.addEventListener("ended", function () {
                                _this.currentFlight.close();
                                _this.currentFlight = _class.getNextMainFlight(_this.currentFlight.index, _this.flights);
                                _this.currentFlight.open(function (flight) {
                                    _this.video.isFullScreen && (viewer.trackedEntity = flight.entity);
                                    _this.video.url = _this.currentFlight.videoURL;
                                    _this.video.play();
                                });
                            }, false);

                            _this.video.onHide = function () {

                                if (_this.video.isFullScreen) {
                                    _this.video.closeFullScreen();
                                }

                                _this.treeNode.closeLayer();
                            };

                            // _this.startVideoTitle = function () {
                            //     _this.stopVideoTitle();
                            //     _this.titleInterval = setInterval(function () {
                            //         var startPosition = _this.currentFlight.mileage.start;
                            //         var stopPosition = _this.currentFlight.mileage.stop;
                            //         var distance = stopPosition - startPosition;
                            //         var timedis = uEarth.JulianDate.secondsDifference(_this.currentFlight.stopTime, _this.currentFlight.startTime) * 1000;
                            //         var currentPosition = Math.floor(startPosition + (new Date(viewer.clock.currentTime).getTime() - new Date(_this.currentFlight.startTime).getTime()) / timedis * distance);
                            //         var pno = Math.floor(currentPosition / 1000);
                            //         var pmile = currentPosition - pno * 1000;
                            //         // var currentPositionText = _this.currentFlight.router + "-K" + pno + "+" + pmile + "m" + " (" + _this.currentFlight.folder + "/" + _this.currentFlight.file + ")";
                            //         var currentPositionText = _this.currentFlight.router + "-K" + pno + "+" + pmile + "m" + " (" + _this.getZHCity(currentPosition) + ")";
                            //         _this.video.dom.find(".title").text(currentPositionText);
                            //     }, 1000);
                            // };
                            //
                            // _this.stopVideoTitle = function () {
                            //     _this.titleInterval && clearInterval(_this.titleInterval);
                            //     _this.video.dom.find(".title").text("无人机视频");
                            // };

                            _this.video.openFullScreen = function () {
                                _this.video.isFullScreen = true;

                                uiApp.left.hide();
                                _this.relocateButton.hide();
                                _class.requestFullScreen(document.documentElement);

                                _this.video.videoDiv.prependTo(uiApp.dom);
                                viewer.clock.shouldAnimate && _this.video.videoDOM.play();
                                uiApp.earth.appendTo(_this.video.dom);

                                viewer.trackedEntity = _this.currentFlight.entity;

                            };

                            _this.video.closeFullScreen = function () {

                                uiApp.left.show();
                                _this.relocateButton.show();
                                _class.exitFullScreen();
                                _this.video.isFullScreen = false;
                                uiApp.earth.prependTo(uiApp.dom);
                                _this.video.videoDiv.appendTo(_this.video.dom);
                                viewer.clock.shouldAnimate && _this.video.videoDOM.play();
                                viewer.trackedEntity = null;

                            };

                            //点击获取最近桩号段轨迹并播放
                            _this.handler = new uEarth.ScreenSpaceEventHandler(umapEarthJs.scene.canvas);
                            _this.handlerFunction = function (e) {
                                var c3p = umapEarthJs.camera.pickEllipsoid(e.position, umapEarthJs.scene.globe.ellipsoid);

                                if (c3p) {

                                    var position = uEarth.Cartographic.fromCartesian(c3p);
                                    var longitude = uEarth.Math.toDegrees(position.longitude);
                                    var latitude = uEarth.Math.toDegrees(position.latitude);

                                    var pickObject = umapEarthJs.scene.pick(e.position);
                                    if (!pickObject || (pickObject.id && !pickObject.id.click)) {
                                        var positionGPS = {
                                            "longitude": longitude,
                                            "latitude" : latitude
                                        };

                                        var targetFlight = _class.getNearestFlight(positionGPS, _this.flights);

                                        _this.videoPlaying = !_this.video.videoDOM.paused;

                                        if (targetFlight) {
                                            if (_this.currentFlight && _this.currentFlight != targetFlight) {

                                                _this.currentFlight.close();
                                                _this.currentFlight = targetFlight;
                                                _this.currentFlight.open(function () {
                                                    _this.video.url = _this.currentFlight.videoURL;
                                                    _this.video.videoDOM.src = _this.currentFlight.videoURL;
                                                    _this.currentFlight.gotoPosition(positionGPS);
                                                    _this.video.videoDOM.currentTime = uEarth.JulianDate.secondsDifference(viewer.clock.currentTime, _this.currentFlight.startTime);
                                                });
                                            } else {
                                                _this.currentFlight.gotoPosition(positionGPS);
                                                _this.video.videoDOM.currentTime = uEarth.JulianDate.secondsDifference(viewer.clock.currentTime, _this.currentFlight.startTime);
                                            }

                                        }
                                    }

                                }
                            };

                        }
                    }
                });

            } else {
                onLoad && onLoad();
            }
        };

        _this.open = function (onOpen) {
            _this.load(function () {

                _this.oldClockRange = umapEarthJs.earthViewer.clock.clockRange;
                umapEarthJs.earthViewer.clock.clockRange = uEarth.ClockRange.UNBOUNDED;

                uiApp.currentFlght && uiApp.currentFlght.treeNode.closeLayer();

                _this.dom.show();
                _this.video.show();
                _this.handler.setInputAction(_this.handlerFunction, uEarth.ScreenSpaceEventType.LEFT_CLICK);
                _this.currentFlight = _this.flights[0];
                _this.currentFlight.open(function () {
                    _this.video.url = _this.currentFlight.videoURL;
                    _this.video.play();

                    uiApp.currentFlght = _this;

                });
                _this.isOpened = true;
                $.each(_this.flights, function (i, flight) {
                    flight.entity && (flight.entity.show = true);
                });
                onOpen && onOpen();
            });
        };

        _this.fly = function () {
            viewer.flyTo(_this.entity, {
                offset: new uEarth.HeadingPitchRange(0, -90, 1000)
            });
        };

        _this.close = function (onClose) {

            if (_this.isLoaded && _this.isOpened) {

                umapEarthJs.earthViewer.clock.clockRange = _this.oldClockRange;

                _this.handler.removeInputAction(uEarth.ScreenSpaceEventType.LEFT_CLICK);
                _this.currentFlight && _this.currentFlight.close();
                _this.currentFlight = undefined;
                _this.dom.hide();
                _this.video.dom.hide();
                _this.video.videoDOM.pause();
                $.each(_this.flights, function (i, flight) {
                    flight.entity.show = false;
                });
                // _this.stopVideoTitle();
            }

            _this.isOpened = false;
            onClose && onClose();

        };

        _this.clear = function (onClear) {

            _this.isOpened = false;
            onClear && onClear();

        };

        _this.toggle = function (onToggle) {

            if (_this.isOpened) {
                _this.close(onToggle);
            } else {
                _this.open(onToggle);
            }

        };

        _this.onInit && _this.onInit(_this);

    }


    var _class = UavFlightsLayer;
    Interface._initAble.call(_class);

    _class.getNextMainFlight = function (index, flights) {

        var resultFlight = flights[0];

        if (index + 1 < flights.length) {
            for (var i = index + 1; i < flights.length; i++) {
                if (flights[i].isMain) {
                    resultFlight = flights[i];
                    break;
                }
            }
        }
        return resultFlight;

    };

    _class.getNearestPosition = function (targetPosition, positions, maxDistance) {

        var nearestDistance;
        var resultPosition;

        $.each(positions, function (i, position) {

            var distance = uEarth.Cartesian2.distance(
                new uEarth.Cartesian2(position.longitude, position.latitude),
                new uEarth.Cartesian2(targetPosition.longitude, targetPosition.latitude)
            );

            if (nearestDistance) {
                if (nearestDistance > distance) {
                    nearestDistance = distance;
                    resultPosition = positions[i];
                }
            } else {
                nearestDistance = distance;
                resultPosition = positions[i];
            }

        });

        return resultPosition;

    };

    _class.getNearestFlight = function (targetPosition, flights) {

        var nearestDistance;
        var resultFlight;

        $.each(flights, function (i, flight) {

            if (_class.inBox(targetPosition, flight.position.start, flight.position.stop) && flight.isMain) {

                resultFlight = flights[i];
                return false;

            } else {


            }

        });

        return resultFlight;

    };

    _class.inBox = function (position, startPosition, stopPosition) {

        return _class.between(position.longitude, startPosition.longitude, stopPosition.longitude)
            && _class.between(position.latitude, startPosition.latitude, stopPosition.latitude);

    };

    _class.between = function (target, start, end) {

        var endTarget = end - target;
        var targetStart = target - start;
        var endTargetMultiTargetStart = endTarget * targetStart;
        return endTargetMultiTargetStart >= 0;

    };

    _class.requestFullScreen = function (element) {
        // 判断各种浏览器，找到正确的方法
        var requestMethod = element.requestFullScreen || //W3C
            element.webkitRequestFullScreen || //Chrome等
            element.mozRequestFullScreen || //FireFox
            element.msRequestFullScreen; //IE11
        if (requestMethod) {
            requestMethod.call(element);
        }
        else if (typeof window.ActiveXObject !== "undefined") {//for Internet Explorer
            var wscript = new ActiveXObject("WScript.Shell");
            if (wscript !== null) {
                wscript.SendKeys("{F11}");
            }
        }
    };

    _class.exitFullScreen = function () {
        // 判断各种浏览器，找到正确的方法
        var exitMethod = document.exitFullscreen || //W3C
            document.mozCancelFullScreen || //Chrome等
            document.webkitExitFullscreen || //FireFox
            document.webkitExitFullscreen; //IE11
        if (exitMethod) {
            exitMethod.call(document);
        }
        else if (typeof window.ActiveXObject !== "undefined") {//for Internet Explorer
            var wscript = new ActiveXObject("WScript.Shell");
            if (wscript !== null) {
                wscript.SendKeys("{F11}");
            }
        }
    };


})();